/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.servinf.ani.sincronizador.utils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;

/**
 * Clase que permite la conexión con el FTP de la ANI
 * para descargar el archivo.
 * @author mortiz
 */
public class FTPHelper {
    
    /**
     * Retorna la ruta absoluta del archivo que se acaba de desargar del 
     * servidor FTP.
     * @return 
     */
    public static String downloadFileFromFTP() {
        
        String host = PropertiesHelper.getInstance().getProperties().getProperty("ftp.host");
        String username = PropertiesHelper.getInstance().getProperties().getProperty("ftp.username");
        String password = PropertiesHelper.getInstance().getProperties().getProperty("ftp.password");
        String port = PropertiesHelper.getInstance().getProperties().getProperty("ftp.port"); 
        int portNumber = Integer.parseInt(port);
        //Carpeta donde está el archivo remoto
        String remoteFileName = PropertiesHelper.getInstance().getProperties().getProperty("ftp.file"); 
        String localFolderString = PropertiesHelper.getInstance().getProperties().getProperty("excel.localFolder");
        String localFileName = PropertiesHelper.getInstance().getProperties().getProperty("excel.fileName");
        String extension = PropertiesHelper.getInstance().getProperties().getProperty("excel.format");
        
        FTPClient ftpClient = new FTPClient();
        try {
            ftpClient.connect(host, portNumber);
            ftpClient.login(username, password);
            ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            //Si la carpeta local de excel no existe, creela
            File localFolder = new File(localFolderString);
            if(!localFolder.exists()) {
               localFolder.mkdirs();
            }
            String absolutePath = localFolderString + "\\" + localFileName +"-"+ now() + "." +  extension;
            // APPROACH #1: using retrieveFile(String, OutputStream)
            File downloadFile = new File(absolutePath);
            if(!downloadFile.exists()) {
                downloadFile.createNewFile();
            }
            OutputStream outputStream1 = new BufferedOutputStream(new FileOutputStream(downloadFile));
            boolean success = ftpClient.retrieveFile(remoteFileName, outputStream1);
            outputStream1.close();
 
            if (success) {
                LogHelper.Log(LogHelper.INFO, "Archivo descargado en " + absolutePath, null);
                return absolutePath;
            }
            return null;
        } catch (IOException ex) {
            try {
                LogHelper.Log(LogHelper.ERROR, "Error descargando el archivo excel " + remoteFileName, ex);
            } catch (IOException ex1) {
                Logger.getLogger(FTPHelper.class.getName()).log(Level.SEVERE, null, ex1);
            }
            return null;
        } finally {
            try {
                if (ftpClient.isConnected()) {
                    ftpClient.logout();
                    ftpClient.disconnect();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
    
    
     /**
      * Se retorna la fecha actual.
      * @return 
      */
     private static String now() {
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd_h_m_S");
        return sdf.format(cal.getTime());
    }
    
    
}
